<template>
    <view class="page-box">
        <header class="header"></header>
        <section class="section" style="margin-top: -494rpx;">
            <!-- 材料补充 -->
            <view class="form-box">
                <view class="form-title">材料补充</view>
                <view class="form-item">
                    <view class="upload-list">
                        <view class="box">
                            <view class="area column rowCenter verCenter" @click="chooseImageChange(1)">
                                <template v-if="isVideo(form.order_info_supplement_img_1)">
                                    <video :src="form.order_info_supplement_img_1" object-fit="cover"></video>
                                </template>
                                <template v-else-if="isImage(form.order_info_supplement_img_1)">
                                    <image :src="form.order_info_supplement_img_1" mode="aspectFill"></image>
                                </template>
                                <template v-else-if="isPdf(form.order_info_supplement_img_1)">
                                    <image class="pdf" src="@/static/pdf.png" mode="aspectFit"></image>
                                </template>
                                <view class="delete row rowCenter verCenter" @click.stop="deletePic(1)" v-if="form.order_info_supplement_img_1">
                                    <text class="iconfont icon-shanchu"></text>
                                </view>
                            </view>
                        </view>
                        <view class="box">
                            <view class="area column rowCenter verCenter" @click="chooseImageChange(2)">
                                <template v-if="isVideo(form.order_info_supplement_img_2)">
                                    <video :src="form.order_info_supplement_img_2" object-fit="cover"></video>
                                </template>
                                <template v-else-if="isImage(form.order_info_supplement_img_2)">
                                    <image :src="form.order_info_supplement_img_2" mode="aspectFill"></image>
                                </template>
                                <template v-else-if="isPdf(form.order_info_supplement_img_2)">
                                    <image class="pdf" src="@/static/pdf.png" mode="aspectFit"></image>
                                </template>
                                <view class="delete row rowCenter verCenter" @click.stop="deletePic(2)" v-if="form.order_info_supplement_img_2">
                                    <text class="iconfont icon-shanchu"></text>
                                </view>
                            </view>
                        </view>
                        <view class="box">
                            <view class="area column rowCenter verCenter" @click="chooseImageChange(3)">
                                <template v-if="isVideo(form.order_info_supplement_img_3)">
                                    <video :src="form.order_info_supplement_img_3" object-fit="cover"></video>
                                </template>
                                <template v-else-if="isImage(form.order_info_supplement_img_3)">
                                    <image :src="form.order_info_supplement_img_3" mode="aspectFill"></image>
                                </template>
                                <template v-else-if="isPdf(form.order_info_supplement_img_3)">
                                    <image class="pdf" src="@/static/pdf.png" mode="aspectFit"></image>
                                </template>
                                <view class="delete row rowCenter verCenter" @click.stop="deletePic(3)" v-if="form.order_info_supplement_img_3">
                                    <text class="iconfont icon-shanchu"></text>
                                </view>
                            </view>
                        </view>
                        <view class="box">
                            <view class="area column rowCenter verCenter" @click="chooseImageChange(4)">
                                <template v-if="isVideo(form.order_info_supplement_img_4)">
                                    <video :src="form.order_info_supplement_img_4" object-fit="cover"></video>
                                </template>
                                <template v-else-if="isImage(form.order_info_supplement_img_4)">
                                    <image :src="form.order_info_supplement_img_4" mode="aspectFill"></image>
                                </template>
                                <template v-else-if="isPdf(form.order_info_supplement_img_4)">
                                    <image class="pdf" src="@/static/pdf.png" mode="aspectFit"></image>
                                </template>
                                <view class="delete row rowCenter verCenter" @click.stop="deletePic(4)" v-if="form.order_info_supplement_img_4">
                                    <text class="iconfont icon-shanchu"></text>
                                </view>
                            </view>
                        </view>
                        <view class="box">
                            <view class="area column rowCenter verCenter" @click="chooseImageChange(5)">
                                <template v-if="isVideo(form.order_info_supplement_img_5)">
                                    <video :src="form.order_info_supplement_img_5" object-fit="cover"></video>
                                </template>
                                <template v-else-if="isImage(form.order_info_supplement_img_5)">
                                    <image :src="form.order_info_supplement_img_5" mode="aspectFill"></image>
                                </template>
                                <template v-else-if="isPdf(form.order_info_supplement_img_5)">
                                    <image class="pdf" src="@/static/pdf.png" mode="aspectFit"></image>
                                </template>
                                <view class="delete row rowCenter verCenter" @click.stop="deletePic(5)" v-if="form.order_info_supplement_img_5">
                                    <text class="iconfont icon-shanchu"></text>
                                </view>
                            </view>
                        </view>
                        <view class="box">
                            <view class="area column rowCenter verCenter" @click="chooseImageChange(6)">
                                <template v-if="isVideo(form.order_info_supplement_img_6)">
                                    <video :src="form.order_info_supplement_img_6" object-fit="cover"></video>
                                </template>
                                <template v-else-if="isImage(form.order_info_supplement_img_6)">
                                    <image :src="form.order_info_supplement_img_6" mode="aspectFill"></image>
                                </template>
                                <template v-else-if="isPdf(form.order_info_supplement_img_6)">
                                    <image class="pdf" src="@/static/pdf.png" mode="aspectFit"></image>
                                </template>
                                <view class="delete row rowCenter verCenter" @click.stop="deletePic(6)" v-if="form.order_info_supplement_img_6">
                                    <text class="iconfont icon-shanchu"></text>
                                </view>
                            </view>
                        </view>
                    </view>
                </view>
            </view>
            <view class="btn row rowCenter verCenter" @click="submit()">保存</view>
        </section>
    </view>
</template>

<script>
    import { API } from '@/util/api.js';
    export default {
        data() {
            return {
                checkingSupplyInfo: {}, //验证只管是否配置显示
                form: {
                    "order_id": "",
                    "order_info_supplement_img_1": "",
                    "order_info_supplement_img_2": "",
                    "order_info_supplement_img_3": "",
                    "order_info_supplement_img_4": "",
                    "order_info_supplement_img_5": "",
                    "order_info_supplement_img_6": ""
                }
            };
        },
        onLoad(options) {
            this.form.order_id = options.order_id;
            this.getOrderAddedInfo();
        },
        methods: {
            /**
             * 上传图片
             * @param {Object} elem
             */
            chooseImageChange(elem) {
                uni.chooseFile({
                    count: 1, // 允许选择的文件数量，默认值为 1
                    type: 'all', // 文件类型，可选值有 image、video、audio、all
                    extension: ['png', 'jpg', 'jpeg', 'mp4', 'pdf'], // 允许的文件扩展名
                    success: (res) => {

                        // 显示loading
                        uni.showLoading({
                            title: '上传中...'
                        });

                        // 获取选择的图片路径数组
                        const tempFilePaths = res.tempFilePaths;

                        //上传到服务器
                        uni.uploadFile({
                            url: API.uploadImage,
                            filePath: tempFilePaths[0],
                            name: 'file',
                            formData: {
                                'source': 'appUser'
                            },
                            success: uploadFileRes => {
                                console.log('服务器上传图片成功：', uploadFileRes);
                                uni.hideLoading();
                                let data = JSON.parse(uploadFileRes.data);
                                if (data.code === 0) {
                                    const formMapping = {
                                        1: "order_info_supplement_img_1",
                                        2: "order_info_supplement_img_2",
                                        3: "order_info_supplement_img_3",
                                        4: "order_info_supplement_img_4",
                                        5: "order_info_supplement_img_5",
                                        6: "order_info_supplement_img_6"
                                    };
                                    // 根据 elem 更新相应的表单数据
                                    if (formMapping[elem]) {
                                        this.$set(this.form, formMapping[elem], data.data);
                                    } else {
                                        console.warn('未识别的 elem:', elem);
                                    }
                                    this.$forceUpdate();
                                } else {
                                    uni.showToast({
                                        title: data.msg,
                                        icon: 'none'
                                    });
                                }
                            },
                            fail: () => {
                                uni.hideLoading();
                                uni.showToast({
                                    title: '上传图片失败',
                                    icon: 'none'
                                });
                            }
                        });
                    }
                });
            },
            /**
             * 删除图片
             * @param {Object} elem
             */
            deletePic(elem) {
                const formMapping = {
                    1: "order_info_supplement_img_1",
                    2: "order_info_supplement_img_2",
                    3: "order_info_supplement_img_3",
                    4: "order_info_supplement_img_4",
                    5: "order_info_supplement_img_5",
                    6: "order_info_supplement_img_6"
                }


                // 检查 elem 是否在映射中，并将对应的表单字段设置为空
                if (formMapping.hasOwnProperty(elem)) {
                    this.$set(this.form, formMapping[elem], '');
                } else {
                    console.warn('未识别的 elem:', elem);
                }
            },
            /**
             * 预览图片
             * @param {Object} img
             */
            previewChange(img) {
                uni.previewImage({
                    urls: [img]
                });
            },
            /**
             * 进件字段配置信息
             */
            getCheckingSupplyInfo() {
                this.request(API.getCheckingSupplyInfo, 'GET', { order_id: this.form.order_id }, true).then(res => {
                    if (res.code === 0) {
                        this.checkingSupplyInfo = res.data;
                    } else {
                        // 获取信息失败的情况下，直接跳转
                        uni.redirectTo({
                            url: `/pages/order/selfDetail?order_id=${this.form.order_id}`
                        });
                    }
                });
            },
            /**
             * 获取进件已经填写的资料
             */
            getOrderAddedInfo() {
                this.request(API.getOrderAddedInfo, 'GET', { order_id: this.form.order_id }, true).then(res => {
                    // 遍历 res 对象，将除了 order_id 之外的所有字段赋值给 this.form
                    Object.keys(res).forEach(key => {
                        if (key !== 'order_id' && this.form.hasOwnProperty(key)) {
                            this.$set(this.form, key, res[key]);
                        }
                    });
                }).catch(error => {
                    console.error('获取进件资料失败:', error);
                    uni.showToast({
                        title: '获取资料失败，请重试',
                        icon: 'none'
                    });
                });
            },
            /**
             * 提交
             */
            submit() {
                this.request(API.submitApproveAddSupplementInfo, 'POST', this.form, true).then(res => {
                    if (res.code === 0) {
                        uni.showToast({
                            title: '提交成功',
                            icon: 'success',
                            duration: 2000
                        });

                        // 等待2秒后再回到上一页
                        setTimeout(() => {
                            uni.redirectTo({
                                url: "/pages/order/approveAddInfo?order_id=" + this.form.order_id
                            })
                        }, 2000);
                    } else {
                        uni.showToast({
                            title: res.msg,
                            icon: 'none'
                        });
                    }
                }).catch(error => {
                    console.error('提交失败:', error);
                    uni.showToast({
                        title: '提交失败，请重试',
                        icon: 'none'
                    });
                });
            },
            /**
             * 判断文件是否为视频
             * @param {Object} file
             */
            isVideo(file) {
                if (file) {
                    return file.endsWith('.mp4') || file.endsWith('.mov') || file.endsWith('.avi'); // 可以根据需要增加其他视频格式
                }
            },
            /**
             * 判断文件是否为图片
             * @param {Object} file
             */
            isImage(file) {
                if (file) {
                    return (
                        file.endsWith('.jpg') ||
                        file.endsWith('.jpeg') ||
                        file.endsWith('.png') ||
                        file.endsWith('.gif') ||
                        file.endsWith('.bmp')
                    );
                }
            },
            /**
             * 判断文件是否为PDF
             * @param {Object} file
             */
            isPdf(file) {
                if (file) {
                    return file.endsWith('.pdf');
                }
            }
        }
    };
</script>

<style scoped lang="scss">
    @import '@/assets/css/order/approveAddBaseInfo.scss';
</style>